package com.android.fragmentdemo.definervlayoutmanager;

import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class CustomLayoutManager extends RecyclerView.LayoutManager {

    private int mSumDy = 0;
    private int mTotalHeight = 0;

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        removeAllViews();
        detachAndScrapAttachedViews(recycler);
        int offsetY = 0;
        for (int i = 0; i < getItemCount(); i++) {
            View child = recycler.getViewForPosition(i);
            child.setRotationX(5);
            addView(child);
            measureChildWithMargins(child, 0, 0);
            int mWidth = getDecoratedMeasuredWidth(child);
            int mHeight = getDecoratedMeasuredHeight(child);
            //Log.d("dataItem111", "mWidth:" + child.getMeasuredWidth());
            //Log.d("dataItem111", "mHeight:" + child.getMeasuredHeight());
            layoutDecoratedWithMargins(child, 0, offsetY, mWidth, offsetY + mHeight);
            offsetY += mHeight;
        }
        //如果所有子view的高度和没有填满RecyclerView,则将高度设置为RecyclerView高度
        mTotalHeight = Math.max(offsetY, getVerticalSpace());
    }

    @Override
    public boolean canScrollVertically() {
        return true;
    }

    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        int travel = dy;
        if (mSumDy + dy < 0) {
            //滑动到最顶部
            travel = -mSumDy;
        } else if (mSumDy + dy > mTotalHeight - getVerticalSpace()) {
            //滑动底部
            travel = mTotalHeight - getVerticalSpace() - mSumDy;
        }
        mSumDy += travel;
        //平移容器中的item
        offsetChildrenVertical(-travel);
        return dy;
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
       return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onMeasure(@NonNull RecyclerView.Recycler recycler, @NonNull RecyclerView.State state, int widthSpec, int heightSpec) {
        super.onMeasure(recycler, state, widthSpec, heightSpec);
    }

    private int getVerticalSpace() {
        return getHeight() - getPaddingTop() - getPaddingBottom();
    }
}
